﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Newtonsoft.Json
{
    using System.IO;
    public static class JsonHelper
    {
        /// <summary>
        /// 将对象Json序列化并写入指定的数据流
        /// </summary>
        /// <param name="source"></param>
        /// <param name="stream"></param>
        /// <param name="indented"></param>
        public static void SerializeToStream(object source, Stream stream, bool indented = true, Encoding encoding = null)
        {
            var data = JsonConvert.SerializeObject(source, indented ? Formatting.Indented : Formatting.None);
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            var sw = new StreamWriter(stream, encoding);

            sw.Write(data);
            sw.Flush();

        }
        /// <summary>
        /// 将对象Json序列化并写入指定的文件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="filename"></param>
        /// <param name="indented"></param>
        /// <param name="encoding"></param>
        public static void SerializeToFile(object source, string filename, bool indented = true, Encoding encoding = null)
        {
            using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
            {
                SerializeToStream(source, fs, indented, encoding);
            }
        }
        /// <summary>
        /// 从文件读取json数据并反序列化成指定的对象。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filename"></param>
        /// <param name="indented"></param>
        /// <param name="encoding"></param>
        public static T DeserializeFromFile<T>(string filename, Encoding encoding = null)
        {
            if (!File.Exists(filename))
            {
                return default(T);
            }
            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                using (var sr = new StreamReader(fs, encoding ?? Encoding.UTF8))
                {
                    var data = sr.ReadToEnd();
                    return JsonConvert.DeserializeObject<T>(data);
                }
            }
        }

    }
}
